﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace MonoTouchAutoBind
{
    class BindTypedefBlock : MonotouchBind
    {
        private string patternStart = @"typedef\s+(?!enum)(?'returnType'\w+)\s*\(\s*\^\s*(?'delegateType'\w+)\s*\)\s*\(\s*(?'params'[*\s\w,]*)\s*\)\s*;";
        private System.Text.RegularExpressions.Regex regex = null;


        private bool noParam;
        public string returnType, delegateType;
        public string paramString = "";


        public override string EndString
        {
            get
            {
                return ";";
            }
        }

        public BindTypedefBlock()
            : base()
        {
            regex = new System.Text.RegularExpressions.Regex(patternStart);
        }

        public override bool CanParse(string code)
        {
            return regex.IsMatch(code);
        }

        public override int PushCode(string code)
        {
            this.ParseFiniseStatus = ParseStatus.Processing;
            this.BindCode = code;

            if (this.CanParse(code))
            {
                System.Text.RegularExpressions.Match match = regex.Match(code);
                returnType = match.Groups["returnType"].Value.Replace("*", "").Trim();
                delegateType = match.Groups["delegateType"].Value.Trim();
                paramString = match.Groups["params"].Value.Trim();
                noParam = (paramString.Length == 0);

                this.ParseFiniseStatus = ParseStatus.Finished;
                return match.Length;
            }
            else
            {
                this.ParseFiniseStatus = ParseStatus.Finished;
                DebugOut.Instance.Print(code);
                return 0;
            }
        }



        public override string GenerateCSharp()
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("//" + this.BindCode);
            if (BindBlock.CanParse(this.BindCode.Trim().Substring(7)))
            {
                string delegateCode;
                if (BindBlock.GenerateCSharp(delegateType, this.BindCode.Trim().Substring(7), out delegateCode))
                {
                    sb.AppendLine(delegateCode);
                }
            }
            return sb.ToString();
        }


    }
}
